package com.matriq.cloudmanager.fragment;

import java.util.Arrays;
import java.util.List;

import com.matriq.cloudmanager.R;
import com.matriq.cloudmanager.PlayerActivity;
import com.matriq.cloudmanager.entity.CourseInfo;
import com.matriq.cloudmanager.entity.db.DownloadCourseInfo;
import com.matriq.cloudmanager.service.DownloadRecevicer;
import com.matriq.cloudmanager.service.DownloadService;
import com.matriq.cloudmanager.service.DownloadService.DownloadBinder;
import com.matriq.cloudmanager.service.DownloadService.ServiceDownloadTask;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import net.lgpage.fragment.BaseFragment;
import net.lgpage.http.ExceptionAsyncTask;
import net.lgpage.http.SwipeRefeshAsyncTask;
import net.lgpage.util.Cleaner;

public class CourseCenterFragment extends BaseFragment {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fm_course_center, container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		setViews();
		setEvents();
		loadData();
	}

	android.support.v7.widget.RecyclerView rcy_course_center;
	android.support.v4.widget.SwipeRefreshLayout srl;
	TextView tv_tab[] = new TextView[3];
	RelativeLayout rl_tab[] = new RelativeLayout[3];
	EditText et_search;

	private void setViews() {
		rcy_course_center = (android.support.v7.widget.RecyclerView) getView().findViewById(R.id.rcy_course_center);
		rcy_adp = new RcyAdp();
		rcy_course_center.setLayoutManager(new LinearLayoutManager(getActivity()));
		rcy_course_center.setAdapter(rcy_adp);
		srl = (android.support.v4.widget.SwipeRefreshLayout) getView().findViewById(R.id.srl);
		tv_tab[0] = (TextView) getView().findViewById(R.id.tv_tab0);
		tv_tab[1] = (TextView) getView().findViewById(R.id.tv_tab1);
		tv_tab[2] = (TextView) getView().findViewById(R.id.tv_tab2);
		rl_tab[0] = (RelativeLayout) getView().findViewById(R.id.rl_tab0);
		rl_tab[1] = (RelativeLayout) getView().findViewById(R.id.rl_tab1);
		rl_tab[2] = (RelativeLayout) getView().findViewById(R.id.rl_tab2);
		et_search = (EditText) getView().findViewById(R.id.et_search);
	}

	private void setEvents() {
		srl.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				refeshRcyList();
			}
		});
	}

	ObjTask objTask;

	public void putObj() {
		if (objTask != null) {
			objTask.cancel(true);
		}
		objTask = new ObjTask(getActivity());
		objTask.execute();
	}

	private class ObjTask extends ExceptionAsyncTask<Object> {

		public ObjTask(Context context) {
			super(context);
		}

		@Override
		public Object doInBackgroundX(String... params) throws Exception {
			return null;
		}

		@Override
		public void onPostExecuteX(Object result) {
			if (result == null) {
				return;
			} else {
				obj = result;
				// Snackbar.make(getView(), "成功", 1).show();
			}
		}
	}

	Object obj;

	public void setData(Object obj) {
		this.obj = obj;
		tv_tab[0].setText(null);
		tv_tab[1].setText(null);
		tv_tab[2].setText(null);
		et_search.setText(null);
		et_search.setSelection(et_search.length());
	}

	private class RcyViewHolder extends RecyclerView.ViewHolder {
		LinearLayout ll;
		ImageView iv;
		ProgressBar pb;
		TextView tv[] = new TextView[4];
		LinearLayout ll_progress;
		Button bt[] = new Button[2];

		public RcyViewHolder(View view) {
			super(view);
		}
	}

	RcyAdp rcy_adp;

	class RcyAdp extends RecyclerView.Adapter<RcyViewHolder> {

		LayoutParams lp;

		@Override
		public int getItemCount() {
			if (rcylist == null)
				return 0;
			return rcylist.size();
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		public RcyAdp() {
			super();
			lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
			setHasStableIds(true);
		}

		@Override
		public void onBindViewHolder(RcyViewHolder h, final int position) {
			final CourseInfo obj = rcylist.get(position);
			loadImage(obj.getHeadpic(), h.iv);
			h.tv[0].setText(obj.getTitle());
			h.tv[1].setText(obj.getTimeLength());
			h.tv[2].setText(obj.getScore());
			String url = obj.getUrl();
			if (binder != null) {
				DownloadService s = binder.getService();
				if (s.isDownloading(url)) {
					h.bt[1].setText("暂停");
					setHolderShow(h, View.VISIBLE);
					ServiceDownloadTask task = s.getDownloadTask(url);
					if (task != null) {
						h.tv[2].setText(task.getCurrentPostion() * 1000 / task.getLength() / 10f + "%");
						h.pb.setMax((int) task.getLength());
						h.pb.setProgress((int) task.getCurrentPostion());
					}
				} else if (s.isStop(url)) {
					h.bt[1].setText("下载");
					setHolderShow(h, View.VISIBLE);
					ServiceDownloadTask task = s.getDownloadTask(url);
					if (task != null) {
						h.tv[2].setText(task.getCurrentPostion() * 1000 / task.getLength() / 10f + "%");
						h.pb.setMax((int) task.getLength());
						h.pb.setProgress((int) task.getCurrentPostion());
					}
				} else {
					final String path = (String) load(url, null);
					if (path == null) {
						h.bt[1].setText("下载");
					} else {
						h.bt[1].setText("下载完成");
					}
					setHolderShow(h, View.GONE);
				}
			}
			// h.tv[3].setText(null);
			h.bt[0].setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					toActivity(PlayerActivity.class, obj);
				}
			});
			h.bt[1].setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					DownloadCourseInfo dobj = obj.castToDownloadCourseInfo();
					
					if (binder.getService().isDownloading(obj.getUrl())) {
						binder.getService().stop(obj.getUrl());
					} else {
						binder.getService().download(getItemId(position), obj.getUrl(), null);
					}
				}
			});
			h.itemView.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {

				}
			});
		}

		@SuppressLint("InflateParams")
		@Override
		public RcyViewHolder onCreateViewHolder(ViewGroup vgp, final int position) {
			View cv = getActivity().getLayoutInflater().inflate(R.layout.rcy_course_center, null);
			cv.setLayoutParams(lp);
			RcyViewHolder h = new RcyViewHolder(cv);
			h.ll = (LinearLayout) cv.findViewById(R.id.ll);
			h.iv = (ImageView) cv.findViewById(R.id.iv);
			h.pb = (ProgressBar) cv.findViewById(R.id.pb);
			h.tv[0] = (TextView) cv.findViewById(R.id.tv0);
			h.tv[1] = (TextView) cv.findViewById(R.id.tv1);
			h.tv[2] = (TextView) cv.findViewById(R.id.tv2);
			h.tv[3] = (TextView) cv.findViewById(R.id.tv3);
			h.ll_progress = (LinearLayout) cv.findViewById(R.id.ll_progress);
			h.bt[0] = (Button) cv.findViewById(R.id.bt0);
			h.bt[1] = (Button) cv.findViewById(R.id.bt1);
			return h;
		}
	}

	DownloadBinder binder;
	ServiceConnection downloadConn = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {

		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			binder = (DownloadBinder) service;
		}
	};

	@Override
	public void onStart() {
		Intent it = new Intent();
		it.setClass(getActivity(), DownloadService.class);
		getActivity().startService(it);
		getActivity().bindService(it, downloadConn, Context.BIND_AUTO_CREATE);
		IntentFilter filter = new IntentFilter();
		filter.addAction("net.lgpage.service.download");
		getActivity().registerReceiver(receiver, filter);
		super.onStart();
	}

	private void setHolderShow(RcyViewHolder h, int visiable) {
		h.pb.setVisibility(visiable);
		h.tv[3].setVisibility(visiable);
	}

	BroadcastReceiver receiver = new DownloadRecevicer() {

		@Override
		public void onCancel(long itemId, String url) {
			RcyViewHolder h = (RcyViewHolder) rcy_course_center.findViewHolderForItemId(itemId);
			if (h == null)
				return;
			h.bt[1].setText("下载");
		}

		@Override
		public void onProgressChange(long itemId, String url, long position, long length) {
			RcyViewHolder h = (RcyViewHolder) rcy_course_center.findViewHolderForItemId(itemId);
			if (h == null)
				return;
			h.pb.setProgress((int) position);
			h.pb.setMax((int) length);
			setHolderShow(h, View.VISIBLE);
			h.tv[3].setText(position * 1000 / length / 10f + "%");
			h.bt[1].setText("暂停");
		}

		@Override
		public void onFinish(long itemId, String url, String path) {
			RcyViewHolder h = (RcyViewHolder) rcy_course_center.findViewHolderForItemId(itemId);
			if (h == null)
				return;
			setHolderShow(h, View.GONE);
			h.bt[1].setText("下载完成");
		}

		@Override
		public void onError(long itemId, String url) {
			RcyViewHolder h = (RcyViewHolder) rcy_course_center.findViewHolderForItemId(itemId);
			if (h == null)
				return;
			h.bt[1].setText("下载出错");
		}
	};
	List<CourseInfo> rcylist;
	RcyListTask rcylistTask;

	public void refeshRcyList() {
		if (rcylistTask != null) {
			rcylistTask.cancel(true);
		}
		rcylistTask = new RcyListTask(getActivity());
		rcylistTask.setSwipeLayout(srl);
		rcylistTask.execute();
	}

	private class RcyListTask extends SwipeRefeshAsyncTask<List<CourseInfo>> {

		public RcyListTask(Context context) {
			super(context);
		}

		@Override
		public List<CourseInfo> doInBackgroundX(String... params) throws Exception {
			CourseInfo obj = new CourseInfo();
			obj.setHeadpic("");
			obj.setScore("50");
			obj.setTitle("java");
			obj.setTimeLength("1.5小时");
			obj.setUrl("http://test123-10012456.video.myqcloud.com/sp2.mp4");
			return Arrays.asList(obj);
		}

		@Override
		public void onPostExecuteX(List<CourseInfo> result) {
			if (result == null) {
				return;
			} else {
				rcylist = result;
				rcy_adp.notifyDataSetChanged();
			}
		}
	}

	private void loadData() {

		refeshRcyList();
	}

	@Override
	public void onDestroy() {
		if (downloadConn != null) {
			getActivity().unbindService(downloadConn);
			downloadConn = null;
		}
		getActivity().unregisterReceiver(receiver);
		Cleaner.cleanTask(rcylistTask);
		super.onDestroy();
	}

}